package com.infore.airsupervise.service;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.infore.airsupervise.R;
import com.infore.airsupervise.bean.UserE;
import com.infore.airsupervise.biz.UserLocationBiz;
import com.infore.airsupervise.biz.impl.UserLocationBizImpl;
import com.infore.airsupervise.http.BaseResponse;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.service.inter.ProcessConnection;

/**
 * 主服务
 * <p>
 * 作者: dingxinlin
 * 创建日期: 2017/4/22 14:12
 */

public class MainService extends Service {

    private MainBinder mainBinder;
    private SubServiceConnection subConn;

    private UserLocationBiz userLocationBiz;

    private int locationInterval = 5 * 1000 * 60; // 定位间隔时间
    private int effDistance = 100; // 有效距离，单位为米
    public AMapLocationClient locationClient = null;


    @Override
    public void onCreate() {
        super.onCreate();
        if (mainBinder == null) {
            mainBinder = new MainBinder();
        }
        subConn = new SubServiceConnection();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        if (userLocationBiz == null) {
            userLocationBiz = new UserLocationBizImpl();
        }

        if(locationClient == null) {
            locationClient = new AMapLocationClient(getApplicationContext());
            locationClient.setLocationListener(locationListener);
            // 定位参数
            AMapLocationClientOption option = new AMapLocationClientOption();
            option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            option.setInterval(locationInterval);
            //设置定位参数
            locationClient.setLocationOption(option);
            //启动定位
            locationClient.startLocation();
        }

        return mainBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        // 销毁定位服务
        if (locationClient != null) {
            locationClient.stopLocation();
            locationClient.onDestroy();
        }
        locationClient = null;
        return super.onUnbind(intent);
    }

    /**
     * 服务被启动
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 绑定子服务
        this.bindService(new Intent(this, SubService.class), subConn, Context.BIND_IMPORTANT);

        // 启动时在通知栏展示通知，以提升优先级
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.wg_icon)
                .setContentTitle("大气趋势化")
                .setContentText("持续为您提供服务");
        // 前台运行，避免休眠被杀死
        startForeground(1, builder.build());

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbindService(subConn);
    }

    /**
     * 提交用户位置到服务器
     * @param aMapLocation
     */
    private void commitUserLocation(AMapLocation aMapLocation) {
        userLocationBiz.commitUserLocationRequest(
                UserE.getUserInfo().getUserId(),
                aMapLocation.getLatitude(),
                aMapLocation.getLongitude(),
                aMapLocation.getAddress(),
                new OnServerResponseListener<BaseResponse>() {
            @Override
            public void onSucceed(BaseResponse result, String desc) {
                Log.d("DXL", "用户位置提交成功");
            }

            @Override
            public void onFailed(int errorCode, String title, String desc) {
                Log.d("DXL", "用户位置提交失败：" +title + "  " + desc);
}
        });
                }

    /**
     * 定位监听回调
     */
    private AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation.getErrorCode() == 0) {
                Log.i("DXL", "当前位置：" + aMapLocation.getAddress());

                // 获取最后一次、当前的经纬度
                LatLng lastLatLng = userLocationBiz.getLastLatLng();
                LatLng curLatLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());

                // 第一次获取最后一次的经纬度为空
                if (lastLatLng == null) {
                    userLocationBiz.saveCurrentLatLng(curLatLng);
                    commitUserLocation(aMapLocation);
                    return;
                }

                // 计算有效距离
                float distance = AMapUtils.calculateLineDistance(lastLatLng, curLatLng);

                // 有效距离小于设定值
                if (distance < effDistance) {
                    Log.w("DXL", "用户移动距离："+ distance +"米，小于有效距离：" + effDistance);
                    return;
                }

                // 提交
                userLocationBiz.saveCurrentLatLng(curLatLng);
                commitUserLocation(aMapLocation);
            } else {
                String[] eInfo = aMapLocation.getErrorInfo().split(" ");
                Log.e("DXL", " 定位失败：" + eInfo[0]);
            }
        }
    };


    /**
     * Main Binder
     */
    private class MainBinder extends ProcessConnection.Stub {

        @Override
        public void getProcessName() throws RemoteException {
//            Log.i("DXL", "getProcessName：Main Service");
        }
    }

    /**
     * 连接子服务的回调
     */
    private class SubServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
//            Log.i("DXL", "子服务连接成功");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
//            Log.i("DXL", "子服务被杀死");
            // 这时先启动子服务
            MainService.this.startService(new Intent(MainService.this, SubService.class));
            // 再绑定子服务
            MainService.this.bindService(
                    new Intent(MainService.this, SubService.class), subConn, Context.BIND_IMPORTANT);
        }
    }
}
